package com.xiaojun.whut.Config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * @author 鲁佳磊
 * @create 2020-10-31 21:02
 */
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    @Lazy
    private BCryptPasswordEncoder passwordEncoder;
    //根据得到的用户名还有密码来进行认证
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = authentication.getName();// 这个获取表单输入中返回的用户名;
        String password = (String) authentication.getCredentials();// 这个是表单中输入的密码；
        System.out.println("测试得到这个用户名还有这个密码");
        System.out.println(userName+"------------"+password);
        UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
        System.out.println(userDetails.getPassword());// 这里调用我们的自己写的获取用户的方法；
        System.out.println(passwordEncoder.matches(password, userDetails.getPassword()));
        if (userDetails == null) {
            throw new BadCredentialsException("用户名不存在");
        }
        if (!passwordEncoder.matches(password,userDetails.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        return new UsernamePasswordAuthenticationToken(userDetails,password, authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }

}
